/**
 * 矩阵树图数据转换工具类 - 优化版
 * 专门处理新的轻量级API返回的数据，构建层次结构以支持超过10000个文件
 */

export interface FileTreeNode {
  path: string;
  lines: number;
  size?: number;
  lang?: string;
}

export interface TreeMapNode {
  name: string;
  value: number;
  path?: string;
  language?: string;
  children?: TreeMapNode[];
}

/**
 * 将扁平的文件列表转换为层次树结构
 * 专门针对新的/treemap/files API优化
 */
export function buildFileHierarchy(files: FileTreeNode[]): TreeMapNode[] {
  if (!files || files.length === 0) {
    return [];
  }

  // 使用Map来提高查找性能
  const pathMap = new Map<string, TreeMapNode>();
  const root: TreeMapNode = { name: 'root', value: 0, children: [] };
  pathMap.set('', root);

  // 按路径层级排序，确保父目录先创建
  const sortedFiles = [...files].sort((a, b) => {
    const depthA = a.path.split('/').length;
    const depthB = b.path.split('/').length;
    return depthA - depthB;
  });

  for (const file of sortedFiles) {
    if (!file.path || !file.lines || file.lines <= 0) {
      continue; // 跳过无效数据
    }

    const pathParts = file.path.split('/').filter(part => part.length > 0);
    let currentPath = '';
    let currentNode = root;

    // 构建路径层级
    for (let i = 0; i < pathParts.length; i++) {
      const part = pathParts[i];
      const parentPath = currentPath;
      currentPath = currentPath ? `${currentPath}/${part}` : part;

      let childNode = pathMap.get(currentPath);
      
      if (!childNode) {
        const isFile = i === pathParts.length - 1;
        childNode = {
          name: part,
          value: isFile ? file.lines : 0,
          path: currentPath,
          language: isFile ? file.lang : undefined,
          children: isFile ? undefined : []
        };
        
        pathMap.set(currentPath, childNode);
        
        // 添加到父节点
        if (!currentNode.children) {
          currentNode.children = [];
        }
        currentNode.children.push(childNode);
      } else if (i === pathParts.length - 1) {
        // 更新文件节点的值（如果已存在）
        childNode.value = file.lines;
        childNode.language = file.lang;
      }
      
      currentNode = childNode;
    }
  }

  // 递归计算目录节点的总值
  function calculateDirectoryValues(node: TreeMapNode): number {
    if (!node.children || node.children.length === 0) {
      return node.value || 0; // 文件节点
    }
    
    // 目录节点：计算所有子节点的总和
    let totalValue = 0;
    for (const child of node.children) {
      totalValue += calculateDirectoryValues(child);
    }
    node.value = totalValue;
    return totalValue;
  }

  calculateDirectoryValues(root);

  // 过滤掉空的节点
  function filterEmptyNodes(nodes: TreeMapNode[]): TreeMapNode[] {
    return nodes
      .filter(node => node.value > 0)
      .map(node => ({
        ...node,
        children: node.children ? filterEmptyNodes(node.children) : undefined
      }))
      .filter(node => node.value > 0 && (node.children === undefined || node.children.length > 0));
  }

  const result = root.children ? filterEmptyNodes(root.children) : [];
  
  // 按值降序排序
  result.sort((a, b) => b.value - a.value);
  
  return result;
}

/**
 * 为大数据量场景优化的数据转换
 * 支持懒加载和数据分片
 */
export function buildOptimizedHierarchy(files: FileTreeNode[], maxNodes = 5000): TreeMapNode[] {
  if (!files || files.length === 0) {
    return [];
  }

  // 如果文件数量不多，直接使用标准方法
  if (files.length <= maxNodes) {
    return buildFileHierarchy(files);
  }

  // 大数据量优化：按代码行数排序，只处理前N个最大的文件
  const topFiles = [...files]
    .filter(f => f.lines > 0)
    .sort((a, b) => b.lines - a.lines)
    .slice(0, maxNodes);

  console.log(`优化处理：从 ${files.length} 个文件中选取前 ${topFiles.length} 个最大文件`);
  
  return buildFileHierarchy(topFiles);
}

/**
 * 生成统计信息
 */
export function generateTreeMapStats(files: FileTreeNode[]) {
  if (!files || files.length === 0) {
    return {
      totalFiles: 0,
      totalLines: 0,
      languages: [],
      maxFileLines: 0,
      avgFileLines: 0
    };
  }

  const validFiles = files.filter(f => f.lines > 0);
  const totalLines = validFiles.reduce((sum, f) => sum + f.lines, 0);
  const maxFileLines = Math.max(...validFiles.map(f => f.lines));
  const avgFileLines = Math.round(totalLines / validFiles.length);

  // 语言统计
  const langMap = new Map<string, { count: number; lines: number }>();
  for (const file of validFiles) {
    if (file.lang) {
      const existing = langMap.get(file.lang) || { count: 0, lines: 0 };
      existing.count++;
      existing.lines += file.lines;
      langMap.set(file.lang, existing);
    }
  }

  const languages = Array.from(langMap.entries())
    .map(([lang, stats]) => ({
      language: lang,
      fileCount: stats.count,
      totalLines: stats.lines,
      percentage: ((stats.lines / totalLines) * 100).toFixed(1)
    }))
    .sort((a, b) => b.totalLines - a.totalLines);

  return {
    totalFiles: validFiles.length,
    totalLines,
    languages,
    maxFileLines,
    avgFileLines
  };
}

// 兼容旧API的转换函数（保留用于向后兼容）
export function transformFullDataToLegacyFormat(packageData: any[], fileData: any[]) {
  console.warn('使用了旧的转换函数，建议升级到新的 buildFileHierarchy');
  
  // 将旧格式转换为新的FileTreeNode格式
  const files: FileTreeNode[] = [];
  
  if (fileData && Array.isArray(fileData)) {
    for (const file of fileData) {
      if (file.filePath && file.codeLines > 0) {
        files.push({
          path: file.filePath,
          lines: file.codeLines,
          size: file.fileSize,
          lang: file.language
        });
      }
    }
  }
  
  return buildFileHierarchy(files);
}